<template>
  <div class="chat-workspace">
    <!-- 左侧：会话列表 -->
    <div class="session-list">
      <div class="session-list-header">
        <h3>会话列表</h3>
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="等待接入" name="waiting">
            <template #label>
              <span>等待接入 <el-badge v-if="waitingCount > 0" :value="waitingCount" /></span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="进行中" name="active" />
          <el-tab-pane label="已关闭" name="closed" />
        </el-tabs>
      </div>
      
      <div class="session-items">
        <div 
          v-for="session in sessions" 
          :key="session.id"
          class="session-item"
          :class="{ active: currentSessionId === session.id }"
          @click="selectSession(session.id)"
        >
          <el-avatar :src="session.member?.avatar || '/default-avatar.png'" :size="48" />
          <div class="session-info">
            <div class="session-name">
              {{ session.member?.nickname || session.member?.username || '未知用户' }}
              <el-tag v-if="session.status === 'WAITING'" type="warning" size="small">等待</el-tag>
              <el-tag v-else-if="session.status === 'ACTIVE'" type="success" size="small">进行中</el-tag>
            </div>
            <div class="session-last-message">
              {{ session.lastMessage?.content || session.title }}
            </div>
          </div>
          <div class="session-meta">
            <div class="session-time">{{ formatTime(session.lastMessageAt || session.createdAt) }}</div>
            <el-badge v-if="session.unreadCount > 0" :value="session.unreadCount" class="session-badge" />
          </div>
        </div>
        
        <el-empty v-if="sessions.length === 0" description="暂无会话" />
      </div>
    </div>

    <!-- 中间：聊天窗口 -->
    <div class="chat-window">
      <div v-if="currentSessionId" class="chat-container">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-user-info">
            <el-avatar :src="currentSession?.member?.avatar || '/default-avatar.png'" :size="40" />
            <div class="user-details">
              <div class="user-name">
                {{ currentSession?.member?.nickname || currentSession?.member?.username }}
              </div>
              <div class="user-status">
                <span :class="['status-dot', isUserOnline ? 'online' : 'offline']"></span>
                {{ isUserOnline ? '在线' : '离线' }}
              </div>
            </div>
          </div>
          <div class="chat-actions">
            <el-button 
              v-if="currentSession?.status === 'WAITING'" 
              type="primary" 
              size="small"
              @click="takeSession"
            >
              接入会话
            </el-button>
            <el-button 
              v-if="currentSession?.status === 'ACTIVE'" 
              size="small"
              @click="showTransferDialog = true"
            >
              转接
            </el-button>
            <el-button 
              v-if="currentSession?.status === 'ACTIVE'" 
              size="small"
              @click="showCloseDialog = true"
            >
              关闭会话
            </el-button>
          </div>
        </div>

        <!-- 聊天消息区 -->
        <div ref="messageContainer" class="chat-messages" @scroll="handleScroll">
          <div v-for="message in messages" :key="message.id" :class="['message-item', message.senderType === 'STAFF' ? 'message-right' : 'message-left']">
            <el-avatar :src="message.senderAvatar || '/default-avatar.png'" :size="36" />
            <div class="message-content-wrapper">
              <div class="message-sender">
                {{ message.senderName }}
                <span class="message-time">{{ formatMessageTime(message.createdAt) }}</span>
              </div>
              <div v-if="!message.isRecalled" class="message-content">
                <!-- 文本消息 -->
                <div v-if="message.messageType === 'TEXT'" class="message-text">
                  {{ message.content }}
                </div>
                <!-- 图片消息 -->
                <div v-else-if="message.messageType === 'IMAGE'" class="message-image">
                  <el-image 
                    :src="message.fileUrl" 
                    :preview-src-list="[message.fileUrl]"
                    fit="cover"
                    style="max-width: 300px; max-height: 200px; border-radius: 8px;"
                  />
                </div>
                <!-- 文件消息 -->
                <div v-else-if="message.messageType === 'FILE'" class="message-file">
                  <el-icon><Document /></el-icon>
                  <div>
                    <div>{{ message.fileName }}</div>
                    <div class="file-size">{{ formatFileSize(message.fileSize) }}</div>
                  </div>
                  <el-button link type="primary" @click="downloadFile(message.fileUrl, message.fileName)">
                    下载
                  </el-button>
                </div>
                <!-- 系统消息 -->
                <div v-else-if="message.messageType === 'SYSTEM'" class="message-system">
                  {{ message.content }}
                </div>
              </div>
              <div v-else class="message-recalled">
                该消息已被撤回
              </div>
              <!-- 消息操作 -->
              <div v-if="!message.isRecalled && message.senderType === 'STAFF'" class="message-actions">
                <el-button v-if="canRecall(message)" link type="primary" size="small" @click="recallMessage(message.id)">
                  撤回
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天输入区 -->
        <div class="chat-input-area">
          <div class="input-toolbar">
            <el-button :icon="Picture" circle @click="selectImage" />
            <el-button :icon="Document" circle @click="selectFile" />
            <el-button :icon="ChatDotRound" circle @click="showQuickReplyPanel = !showQuickReplyPanel">
              快捷回复
            </el-button>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              style="display: none" 
              @change="handleImageSelect"
            />
            <input 
              ref="documentInput" 
              type="file" 
              style="display: none" 
              @change="handleFileSelect"
            />
          </div>
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息内容..."
            @keydown.enter.exact.prevent="sendTextMessage"
          />
          <div class="input-actions">
            <el-button type="primary" @click="sendTextMessage">发送 (Enter)</el-button>
          </div>
        </div>
      </div>

      <!-- 未选择会话 -->
      <el-empty v-else description="请选择一个会话开始聊天" />
    </div>

    <!-- 右侧：用户信息和快捷回复 -->
    <div class="sidebar">
      <el-tabs v-model="sidebarTab">
        <el-tab-pane label="用户信息" name="user">
          <div v-if="currentSession" class="user-info-panel">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="用户名">
                {{ currentSession.member?.username }}
              </el-descriptions-item>
              <el-descriptions-item label="昵称">
                {{ currentSession.member?.nickname || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                {{ currentSession.member?.email || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="手机">
                {{ currentSession.member?.phone || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="会话类型">
                {{ currentSession.type === 'CUSTOMER_SERVICE' ? '客服咨询' : '教练咨询' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDateTime(currentSession.createdAt) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-empty v-else description="暂无用户信息" />
        </el-tab-pane>
        
        <el-tab-pane label="快捷回复" name="quickReply">
          <div class="quick-reply-panel">
            <el-input
              v-model="quickReplySearch"
              placeholder="搜索快捷回复"
              :prefix-icon="Search"
              clearable
              style="margin-bottom: 12px"
            />
            <div class="quick-reply-list">
              <div 
                v-for="reply in filteredQuickReplies" 
                :key="reply.id"
                class="quick-reply-item"
                @click="useQuickReply(reply)"
              >
                <div class="reply-title">{{ reply.title }}</div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>
            <el-empty v-if="filteredQuickReplies.length === 0" description="暂无快捷回复" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 转接对话框 -->
    <el-dialog v-model="showTransferDialog" title="转接会话" width="400px">
      <el-form :model="transferForm">
        <el-form-item label="转接给">
          <el-select v-model="transferForm.toStaffId" placeholder="请选择客服" style="width: 100%">
            <el-option 
              v-for="staff in staffList" 
              :key="staff.id" 
              :label="staff.nickname || staff.username"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTransferDialog = false">取消</el-button>
        <el-button type="primary" @click="handleTransfer">确定</el-button>
      </template>
    </el-dialog>

    <!-- 关闭会话对话框 -->
    <el-dialog v-model="showCloseDialog" title="关闭会话" width="400px">
      <el-form :model="closeForm">
        <el-form-item label="会话评分">
          <el-rate v-model="closeForm.rating" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="closeForm.ratingComment" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCloseDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCloseSession">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Picture, Document, ChatDotRound, Search } from '@element-plus/icons-vue'
import { 
  getSessionList, 
  getWaitingSessions,
  takeSession as apiTakeSession,
  transferSession as apiTransferSession,
  closeSession as apiCloseSession,
  getMessageList,
  sendMessage as apiSendMessage,
  markMessagesAsRead,
  recallMessage as apiRecallMessage,
  uploadChatFile,
  getQuickReplyList,
  getOnlineStatus,
  type ChatSession,
  type ChatMessage,
  type QuickReply
} from '@/api/modules/chat'
import { WebSocketManager, getWebSocketInstance } from '@/utils/websocket'
import { useUserStore } from '@/stores/user'
import { handleApiError, handleWebSocketError, handleUploadError, showSuccess, showWarning } from '@/utils/errorHandler'
import { formatRelativeTime, formatMessageTime, formatDateTime } from '@/utils/dateFormat'
import { formatFileSize, downloadFile } from '@/utils/fileUtils'

// 状态管理
const userStore = useUserStore()
const activeTab = ref('waiting')
const sidebarTab = ref('user')
const sessions = ref<ChatSession[]>([])
const currentSessionId = ref<number | null>(null)
const messages = ref<ChatMessage[]>([])
const inputMessage = ref('')
const quickReplies = ref<QuickReply[]>([])
const quickReplySearch = ref('')
const waitingCount = ref(0)
const showTransferDialog = ref(false)
const showCloseDialog = ref(false)
const showQuickReplyPanel = ref(false)
const staffList = ref<any[]>([])
const onlineUserIds = ref<number[]>([])

// 表单
const transferForm = ref({ toStaffId: null as number | null })
const closeForm = ref({ rating: 5, ratingComment: '' })

// WebSocket
let wsManager: WebSocketManager | null = null

// 当前会话
const currentSession = computed(() => {
  return sessions.value.find(s => s.id === currentSessionId.value)
})

// 用户是否在线
const isUserOnline = computed(() => {
  return currentSession.value?.memberId 
    ? onlineUserIds.value.includes(currentSession.value.memberId)
    : false
})

// 过滤后的快捷回复
const filteredQuickReplies = computed(() => {
  if (!quickReplySearch.value) return quickReplies.value
  return quickReplies.value.filter(reply => 
    reply.title.includes(quickReplySearch.value) || 
    reply.content.includes(quickReplySearch.value)
  )
})

// Refs
const messageContainer = ref<HTMLElement>()
const fileInput = ref<HTMLInputElement>()
const documentInput = ref<HTMLInputElement>()

// 生命周期
onMounted(() => {
  initWebSocket()
  loadSessions()
  loadQuickReplies()
  loadStaffList()
  startOnlineStatusCheck()
})

onUnmounted(() => {
  if (wsManager) {
    wsManager.disconnect()
  }
})

// 监听当前会话变化
watch(currentSessionId, async (newId) => {
  if (newId) {
    await loadMessages(newId)
    scrollToBottom()
  }
})

// 初始化 WebSocket
function initWebSocket() {
  const token = userStore.token
  const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8080/api/v1/chat/ws'
  
  wsManager = getWebSocketInstance(wsUrl, token)
  wsManager.connect().then(() => {
    // 注册消息处理器
    wsManager!.on('NEW_MESSAGE', handleNewMessage)
    wsManager!.on('MESSAGE_READ', handleMessageRead)
    wsManager!.on('SESSION_UPDATE', handleSessionUpdate)
    wsManager!.on('PONG', () => {
      console.log('[WebSocket] 收到心跳响应')
    })
  }).catch(error => {
    ElMessage.error('WebSocket连接失败: ' + error.message)
  })
}

// 处理新消息
function handleNewMessage(data: any) {
  const message = data.data
  if (message.sessionId === currentSessionId.value) {
    messages.value.push(message)
    scrollToBottom()
    // 标记为已读
    markMessagesAsRead({ messageIds: [message.id] })
  } else {
    // 更新未读数
    const session = sessions.value.find(s => s.id === message.sessionId)
    if (session) {
      session.unreadCount++
    }
  }
  // 刷新会话列表
  loadSessions()
}

// 处理消息已读
function handleMessageRead(data: any) {
  const { messageIds } = data.data
  messages.value.forEach(msg => {
    if (messageIds.includes(msg.id)) {
      msg.isRead = true
    }
  })
}

// 处理会话更新
function handleSessionUpdate(data: any) {
  loadSessions()
}

// 加载会话列表
async function loadSessions() {
  try {
    const status = activeTab.value === 'waiting' ? 'WAITING' : 
                   activeTab.value === 'active' ? 'ACTIVE' : 'CLOSED'
    
    const { data } = await getSessionList({ status, page: 1, pageSize: 50 })
    sessions.value = data.list
    
    // 更新等待数量
    if (activeTab.value !== 'waiting') {
      const waitingData = await getWaitingSessions()
      waitingCount.value = waitingData.data.total
    } else {
      waitingCount.value = data.total
    }
  } catch (error: any) {
    ElMessage.error('加载会话列表失败: ' + error.message)
  }
}

// 选择会话
async function selectSession(sessionId: number) {
  currentSessionId.value = sessionId
}

// 加载消息列表
async function loadMessages(sessionId: number) {
  try {
    const { data } = await getMessageList({ sessionId, page: 1, pageSize: 50 })
    messages.value = data.list.reverse() // 反转消息顺序，最新的在下面
    
    // 标记所有消息为已读
    const unreadIds = messages.value.filter(m => !m.isRead && m.senderType === 'MEMBER').map(m => m.id)
    if (unreadIds.length > 0) {
      await markMessagesAsRead({ messageIds: unreadIds })
    }
  } catch (error: any) {
    ElMessage.error('加载消息失败: ' + error.message)
  }
}

// 发送文本消息
async function sendTextMessage() {
  if (!inputMessage.value.trim()) return
  if (!currentSessionId.value) {
    ElMessage.warning('请先选择会话')
    return
  }

  try {
    await apiSendMessage({
      sessionId: currentSessionId.value,
      messageType: 'TEXT',
      content: inputMessage.value.trim()
    })
    inputMessage.value = ''
  } catch (error: any) {
    ElMessage.error('发送消息失败: ' + error.message)
  }
}

// 选择图片
function selectImage() {
  fileInput.value?.click()
}

// 选择文件
function selectFile() {
  documentInput.value?.click()
}

// 处理图片选择
async function handleImageSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  if (!currentSessionId.value) {
    ElMessage.warning('请先选择会话')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('sessionId', currentSessionId.value.toString())

    const { data } = await uploadChatFile(formData)
    
    // 发送图片消息
    await apiSendMessage({
      sessionId: currentSessionId.value,
      messageType: 'IMAGE',
      fileUrl: data.url,
      fileName: data.originalName,
      fileSize: data.size,
      imageWidth: data.width,
      imageHeight: data.height
    })

    ElMessage.success('图片发送成功')
  } catch (error: any) {
    ElMessage.error('图片上传失败: ' + error.message)
  } finally {
    target.value = ''
  }
}

// 处理文件选择
async function handleFileSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  if (!currentSessionId.value) {
    ElMessage.warning('请先选择会话')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('sessionId', currentSessionId.value.toString())

    const { data } = await uploadChatFile(formData)
    
    // 发送文件消息
    await apiSendMessage({
      sessionId: currentSessionId.value,
      messageType: 'FILE',
      fileUrl: data.url,
      fileName: data.originalName,
      fileSize: data.size
    })

    ElMessage.success('文件发送成功')
  } catch (error: any) {
    ElMessage.error('文件上传失败: ' + error.message)
  } finally {
    target.value = ''
  }
}

// 撤回消息
async function recallMessage(messageId: number) {
  try {
    await ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
      type: 'warning'
    })
    
    await apiRecallMessage(messageId)
    const msg = messages.value.find(m => m.id === messageId)
    if (msg) {
      msg.isRecalled = true
    }
    ElMessage.success('消息已撤回')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('撤回失败: ' + error.message)
    }
  }
}

// 判断是否可以撤回（2分钟内）
function canRecall(message: ChatMessage): boolean {
  const now = new Date().getTime()
  const messageTime = new Date(message.createdAt).getTime()
  return (now - messageTime) < 2 * 60 * 1000
}

// 接入会话
async function takeSession() {
  if (!currentSessionId.value) return
  
  try {
    await apiTakeSession(currentSessionId.value)
    ElMessage.success('接入成功')
    loadSessions()
  } catch (error: any) {
    ElMessage.error('接入失败: ' + error.message)
  }
}

// 转接会话
async function handleTransfer() {
  if (!transferForm.value.toStaffId || !currentSessionId.value) return
  
  try {
    await apiTransferSession(currentSessionId.value, {
      toStaffId: transferForm.value.toStaffId
    })
    ElMessage.success('转接成功')
    showTransferDialog.value = false
    loadSessions()
  } catch (error: any) {
    ElMessage.error('转接失败: ' + error.message)
  }
}

// 关闭会话
async function handleCloseSession() {
  if (!currentSessionId.value) return
  
  try {
    await apiCloseSession(currentSessionId.value, {
      rating: closeForm.value.rating,
      ratingComment: closeForm.value.ratingComment
    })
    ElMessage.success('会话已关闭')
    showCloseDialog.value = false
    currentSessionId.value = null
    loadSessions()
  } catch (error: any) {
    ElMessage.error('关闭失败: ' + error.message)
  }
}

// 使用快捷回复
function useQuickReply(reply: QuickReply) {
  inputMessage.value = reply.content
  showQuickReplyPanel.value = false
}

// 加载快捷回复
async function loadQuickReplies() {
  try {
    const { data } = await getQuickReplyList()
    quickReplies.value = data.list
  } catch (error: any) {
    console.error('加载快捷回复失败:', error)
  }
}

// 加载客服列表
async function loadStaffList() {
  // TODO: 实现加载客服列表的API
  staffList.value = []
}

// 开始在线状态检查
function startOnlineStatusCheck() {
  // 初次检查
  checkOnlineStatus()
  
  // 每30秒检查一次
  setInterval(checkOnlineStatus, 30000)
}

// 检查在线状态
async function checkOnlineStatus() {
  try {
    const userIds = sessions.value.map(s => s.memberId)
    const { data } = await getOnlineStatus(userIds)
    onlineUserIds.value = data.onlineUsers
  } catch (error: any) {
    console.error('检查在线状态失败:', error)
  }
}

// 切换标签
function handleTabChange() {
  currentSessionId.value = null
  messages.value = []
  loadSessions()
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

// 处理滚动
function handleScroll() {
  // TODO: 实现滚动加载更多历史消息
}

// 下载文件
function downloadFile(url: string, filename: string) {
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.click()
}

// 时间格式化
function formatTime(time: string): string {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
  
  return date.toLocaleDateString()
}

function formatMessageTime(time: string): string {
  return new Date(time).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

function formatDateTime(time: string): string {
  return new Date(time).toLocaleString('zh-CN')
}

function formatFileSize(bytes?: number): string {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}
</script>

<style scoped lang="scss">
.chat-workspace {
  display: flex;
  height: calc(100vh - 120px);
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

// 左侧会话列表
.session-list {
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;

  .session-list-header {
    padding: 16px;
    border-bottom: 1px solid #e8e8e8;

    h3 {
      margin: 0 0 12px 0;
      font-size: 16px;
    }
  }

  .session-items {
    flex: 1;
    overflow-y: auto;

    .session-item {
      display: flex;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background: #f5f5f5;
      }

      &.active {
        background: #e6f7ff;
      }

      .session-info {
        flex: 1;
        margin-left: 12px;
        min-width: 0;

        .session-name {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 500;
          margin-bottom: 4px;
        }

        .session-last-message {
          font-size: 12px;
          color: #999;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .session-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 4px;

        .session-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

// 中间聊天窗口
.chat-window {
  flex: 1;
  background: white;
  display: flex;

  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #e8e8e8;

      .chat-user-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .user-details {
          .user-name {
            font-weight: 500;
            margin-bottom: 4px;
          }

          .user-status {
            font-size: 12px;
            color: #999;
            display: flex;
            align-items: center;
            gap: 4px;

            .status-dot {
              width: 8px;
              height: 8px;
              border-radius: 50%;

              &.online {
                background: #52c41a;
              }

              &.offline {
                background: #d9d9d9;
              }
            }
          }
        }
      }
    }

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;

      .message-item {
        display: flex;
        margin-bottom: 16px;
        gap: 12px;

        &.message-right {
          flex-direction: row-reverse;

          .message-content-wrapper {
            align-items: flex-end;

            .message-content {
              background: #1890ff;
              color: white;
            }
          }
        }

        .message-content-wrapper {
          display: flex;
          flex-direction: column;
          max-width: 60%;
          gap: 4px;

          .message-sender {
            font-size: 12px;
            color: #999;

            .message-time {
              margin-left: 8px;
            }
          }

          .message-content {
            padding: 12px;
            border-radius: 8px;
            background: #f5f5f5;
            word-break: break-word;

            .message-file {
              display: flex;
              align-items: center;
              gap: 12px;

              .file-size {
                font-size: 12px;
                color: #999;
              }
            }
          }

          .message-recalled {
            padding: 12px;
            color: #999;
            font-style: italic;
          }

          .message-actions {
            font-size: 12px;
          }
        }
      }
    }

    .chat-input-area {
      border-top: 1px solid #e8e8e8;
      padding: 12px;

      .input-toolbar {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
      }

      .input-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 8px;
      }
    }
  }
}

// 右侧边栏
.sidebar {
  width: 300px;
  background: white;
  border-left: 1px solid #e8e8e8;
  overflow-y: auto;

  .user-info-panel {
    padding: 16px;
  }

  .quick-reply-panel {
    padding: 16px;

    .quick-reply-list {
      max-height: 500px;
      overflow-y: auto;

      .quick-reply-item {
        padding: 12px;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          border-color: #1890ff;
          background: #f5f7fa;
        }

        .reply-title {
          font-weight: 500;
          margin-bottom: 4px;
        }

        .reply-content {
          font-size: 12px;
          color: #666;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }
    }
  }
}
</style>

